import express from 'express'
export const router = express.Router()
import { createConnectionPool } from '../../mysql/index.js'
import * as PageUtil from '../../utils/pageutil.js'

const connection = await createConnectionPool()
function FormCheck(form) {
    const { pageSize, pageNum } = form
    if (!pageSize) {
        return {
            err: true,
            message: 'pageSize不能为空'
        }
    }
    if (!pageNum) {
        return {
            err: true,
            message: 'pageNum不能为空'
        }
    }
}
router.get("/user/page", async (req, res) => {
    try {
        const form = req.query
        const verify = FormCheck(form)
        if (verify && verify.err) {
            res.status(500).json({ error: verify.message })
            return
        }
        const { username = null, id = null, pageSize = 10, pageNum = 1 } = req.query
        let countSql = "select count(*) as total from user where deleted = 0"
        if (username && username != 'undefined') {
            countSql += " and username like '%" + username + "%'"
        }
        if (id && id != 'undefined') {
            countSql += " and id ='" + id + "'"
        }
        console.log(countSql, 'countSqlcountSqlcountSqlcountSql');
        const [countRows, countFields] = await connection.execute(countSql)
        const total = countRows[0].total
        const page = PageUtil.toPage(total, pageSize, pageNum)
        console.log(page, 'pagepagepagepage');
        let data = []
        if (page.hasVal) {
            let sql = "select * from user where deleted = 0"
            if (username && username != 'undefined') {
                sql += " and username like '%" + username + "%'"
            }
            if (id && id != 'undefined') {
                sql += " and id ='" + id + "'"
            }
            sql += ` order by create_time desc limit ${page.limit},${page.pageSize}`
            const [rows, fields] = await connection.query(sql)
            const data = rows.map(row => {
                const { user_state, ...rest } = row;
                return { ...rest, user_state: row.user_state == 1 ? true : false };
            });
            res.status(200).send({ code: 200, message: '获取数据成功', data, total })
        }

    } catch (err) {
        console.error('Error fetching user:', err)
        res.status(500).json({ error: '获取数据失败' })
    }
})

function verifyForm(form) {
    const { username, nickname, password, email, points, fee_rate, status, google_key, mistake_count } = form
    if (!username) {
        return {
            err: true,
            msg: '用户名不能为空'
        }
    }
    if (!nickname) {
        return {
            err: true,
            msg: '昵称不能为空'
        }
    }
    if (!password) {
        return {
            err: true,
            msg: '密码不能为空'
        }
    }
    if (!email) {
        return {
            err: true,
            msg: '邮箱不能为空'
        }
    }
    if (!points) {
        return {
            err: true,
            msg: '积分不能为空'
        }
    }
    if (!fee_rate) {
        return {
            err: true,
            msg: '费率不能为空'
        }
    }

    if (status == null || status === '') {
        return {
            err: true,
            msg: '状态不能为空'
        }
    }
    if (!google_key) {
        return {
            err: true,
            msg: '谷歌KEY不能为空'
        }
    }
    if (!mistake_count) {
        return {
            err: true,
            msg: '错误次数不能为空'
        }
    }
    return {
        err: false,
        msg: ''
    }
}

router.post("/user/add", async (req, res) => {
    try {
        const form = req.body
        const verify = verifyForm(form)
        if (verify && verify.err) {
            res.status(500).json({ error: verify.msg })
            return
        }
        const [rows] = await connection.execute(
            'SELECT COUNT(*) as count FROM user WHERE username = ? OR nickname = ?',
            [form.username, form.nickname]
        );

        if (rows[0].count > 0) {
            return res.status(400).send({ code: 400, message: '信息不能重复' });
        }
        const sql = "insert into user (username, nickname, password, email, points, fee_rate, status, mistake_count, google_key, create_time, deleted) values (?,?,?,?,?,?,?,?,?,?,?)"
        await connection.execute(sql, [form.username || null, form.nickname || null, form.password || null, form.email || null, form.points || null, form.fee_rate || null, form.status || 0, form.mistake_count || null, form.google_key || null, new Date(), 0])
        res.status(200).send({ code: 200, message: '新增数据成功' })
    } catch (err) {
        console.error('Error adding user:', err)
        res.status(500).json({ error: '新增数据失败' })
    }
})

router.post("/user/update", async (req, res) => {
    try {
        const form = req.body
        if (!form.id) {
            res.status(500).json({ error: 'id不能为空' })
            return
        }
        const verify = verifyForm(form)
        if (verify.err) {
            res.status(500).json({ error: verify.msg })
            return
        }
        const sql = "update user set username= ?, nickname= ?, password= ?, email= ?, points= ?, fee_rate= ?, status= ?, mistake_count= ?, google_key= ? , superiors = ? ,balance = ? where id = ?"
        await connection.execute(sql, [form.username || null, form.nickname || null, form.password || null, form.email || null, form.points || null, form.fee_rate || null, form.status || 0, form.mistake_count || null, form.google_key || null, form.superiors || null, form.balance || null, form.id])
        res.status(200).send({ code: 200, message: '更新数据成功' })
    } catch (err) {
        console.error('Error updating user:', err)
        res.status(500).json({ error: '更新数据失败' })
    }
})

router.delete("/user/delete", async (req, res) => {
    try {
        const { id } = req.query
        if (!id) {
            res.status(500).json({ error: 'id不能为空' })
            return
        }
        const sql = "update user set deleted = 1 where id = ?"
        await connection.execute(sql, [id])
        res.status(200).send({ code: 200, message: '删除数据成功' })
    } catch (err) {
        console.error('Error deleting user:', err)
        res.status(500).json({ error: '删除数据失败' })
    }
})

router.get("/user/user_state", async (req, res) => {
    const { id, user_state } = req.query;

    try {
        // 执行 SQL 查询更新用户状态
        const [rows] = await connection.execute('UPDATE user SET user_state = ? WHERE id = ?', [user_state, id]);
        if (rows.affectedRows === 0) {
            return res.status(400).json({ message: "用户未找到" });
        }
        res.status(200).json({ code: 200, message: "用户状态更新成功" })
    } catch (error) {
        console.error("更新用户状态时发生错误:", error);
        res.status(500).json({ message: "更新用户状态时发生错误" });
    }
});

export default router;